package com.SNQ.project.English_speaking_learning_system.controller.admin;

import com.SNQ.project.English_speaking_learning_system.common.result.Result;
import com.SNQ.project.English_speaking_learning_system.common.utils.AliOssUtil;
import com.SNQ.project.English_speaking_learning_system.pojo.entity.ReadingRecord;
import com.SNQ.project.English_speaking_learning_system.service.ReadingRecordService;
import com.SNQ.project.English_speaking_learning_system.service.impl.UserServiceImpl;
import com.SNQ.project.English_speaking_learning_system.config.Feedback;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * 通用接口
 */
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private UserServiceImpl userServiceImpl;
    @Autowired
    private ReadingRecordService readingRecordService;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<ReadingRecord> upload(
            @RequestParam("file") MultipartFile file, // 处理文件上传
            @RequestParam("userId") Long userId,      // 处理 userId
            @RequestParam("articleId") Long articleId // 处理 articleId
    ) throws Exception {
        log.info("文件上传：{}",file);
        String audioUrl;

        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //截取原始文件名的后缀 dfdfdf.png
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //访问文件名称
        String objectName = UUID.randomUUID().toString() + extension;

        //文件请求路径
        String filePath = aliOssUtil.upload(file.getBytes(),objectName);
        audioUrl = filePath;


        // 进行语音识别和评分
        int score = userServiceImpl.evaluateAudio(audioUrl,articleId);
        String feedback = Feedback.generateFeedback(score);

        // 设置状态
        boolean status = score > 60;

        // 构建 reading_record 对象
        ReadingRecord readingRecord = new ReadingRecord();
        readingRecord.setUserId(userId);
        readingRecord.setArticleId(articleId);
        readingRecord.setAudioUrl(audioUrl);
        readingRecord.setReadingTime(new Date());
        readingRecord.setScore(score);
        readingRecord.setStatus(status);
        readingRecord.setFeedback(feedback);

        readingRecordService.save(readingRecord);
        return Result.success(readingRecord);

    }
}
